extends Node
class_name FieldSystem

signal tile_changed(pos: Vector2i)
signal stamina_changed(current: int, max_stamina: int)

var field_width := 20
var field_height := 15
var tiles := []

var stamina := 100
var max_stamina := 100

var time_system: TimeSystem
var crop_system: CropSystem
var inventory: Inventory

func _ready():
	initialize_field()

func initialize_field():
	tiles.clear()
	for y in range(field_height):
		var row := []
		for x in range(field_width):
			row.append({
				"plowed": false,
				"wet_until": 0,
				"crop_id": null,
				"stage": 0,
				"planted_time": 0,
				"last_water_time": 0
			})
		tiles.append(row)

func set_time_system(ts: TimeSystem):
	time_system = ts
	if time_system:
		time_system.time_changed.connect(_on_time_changed)

func set_crop_system(cs: CropSystem):
	crop_system = cs

func set_inventory(inv: Inventory):
	inventory = inv

func is_valid_position(pos: Vector2i) -> bool:
	return pos.x >= 0 and pos.x < field_width and pos.y >= 0 and pos.y < field_height

func get_tile(pos: Vector2i) -> Dictionary:
	if not is_valid_position(pos):
		return {}
	return tiles[pos.y][pos.x]

func use_tool(tool: String, pos: Vector2i) -> bool:
	if not is_valid_position(pos):
		return false
	
	var tile = get_tile(pos)
	var success = false
	
	match tool:
		"hoe":
			success = plow_tile(pos, tile)
		"water":
			success = water_tile(pos, tile)
		"seed_turnip", "seed_potato", "seed_corn":
			success = plant_seed(pos, tile, tool)
		"harvest":
			success = harvest_tile(pos, tile)
	
	if success:
		tile_changed.emit(pos)
	
	return success

func plow_tile(pos: Vector2i, tile: Dictionary) -> bool:
	if tile.plowed or tile.crop_id != null:
		return false
	
	if not consume_stamina(5):
		return false
	
	tile.plowed = true
	return true

func water_tile(pos: Vector2i, tile: Dictionary) -> bool:
	if not tile.plowed:
		return false
	
	if not consume_stamina(3):
		return false
	
	var current_time = time_system.get_game_time_stamp() if time_system else 0
	tile.wet_until = current_time + 12  # 湿润12小时
	tile.last_water_time = current_time
	return true

func plant_seed(pos: Vector2i, tile: Dictionary, seed_type: String) -> bool:
	if not tile.plowed or tile.crop_id != null:
		return false
	
	if not inventory.has_item(seed_type, 1):
		return false
	
	var crop_id = seed_type.replace("seed_", "")
	var crop_def = crop_system.get_crop_def(crop_id) if crop_system else {}
	
	if crop_def.is_empty():
		return false
	
	var stamina_cost = crop_def.get("stamina_cost", 2)
	if not consume_stamina(stamina_cost):
		return false
	
	if not inventory.remove_item(seed_type, 1):
		return false
	
	var current_time = time_system.get_game_time_stamp() if time_system else 0
	tile.crop_id = crop_id
	tile.stage = 0
	tile.planted_time = current_time
	tile.last_water_time = current_time
	
	return true

func harvest_tile(pos: Vector2i, tile: Dictionary) -> bool:
	if tile.crop_id == null:
		return false
	
	if not crop_system.is_crop_mature(tile):
		return false
	
	if not consume_stamina(4):
		return false
	
	# 收获作物
	if inventory.add_item(tile.crop_id, 1):
		tile.crop_id = null
		tile.stage = 0
		tile.planted_time = 0
		tile.last_water_time = 0
		return true
	
	return false

func consume_stamina(amount: int) -> bool:
	if stamina >= amount:
		stamina -= amount
		stamina_changed.emit(stamina, max_stamina)
		return true
	return false

func restore_stamina(amount: int):
	stamina = min(max_stamina, stamina + amount)
	stamina_changed.emit(stamina, max_stamina)

func set_stamina(current: int, maximum: int):
	stamina = clamp(current, 0, maximum)
	max_stamina = maximum
	stamina_changed.emit(stamina, max_stamina)

func _on_time_changed(day: int, hour: int):
	# 每小时恢复1点体力
	if hour % 2 == 0:  # 每2小时恢复
		restore_stamina(2)
	
	# 更新所有作物生长状态
	var current_time = time_system.get_game_time_stamp()
	for y in range(field_height):
		for x in range(field_width):
			var tile = tiles[y][x]
			if tile.crop_id != null and crop_system:
				crop_system.update_tile_growth(tile, current_time)

func load_from_data(field_data: Dictionary):
	field_width = field_data.get("width", 20)
	field_height = field_data.get("height", 15)
	
	var tiles_data = field_data.get("tiles", [])
	tiles.clear()
	
	for y in range(field_height):
		var row := []
		for x in range(field_width):
			if y < tiles_data.size() and x < tiles_data[y].size():
				row.append(tiles_data[y][x].duplicate())
			else:
				row.append({
					"plowed": false,
					"wet_until": 0,
					"crop_id": null,
					"stage": 0,
					"planted_time": 0,
					"last_water_time": 0
				})
		tiles.append(row)

func get_save_data() -> Dictionary:
	return {
		"width": field_width,
		"height": field_height,
		"tiles": tiles.duplicate(true)
	}